package com.honghu.villagepost.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.honghu.villagepost.activity.LoginActivity;
import com.honghu.villagepost.constant.Constants;
import com.honghu.villagepost.entity.event.WxLoginEvent;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        IWXAPI api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        try {
            int errCode = baseResp.errCode;
            if (errCode == BaseResp.ErrCode.ERR_OK){
                if (TextUtils.equals(baseResp.transaction, LoginActivity.WXLOGIN_TRANS)) {
                    SendAuth.Resp resp = (SendAuth.Resp) baseResp;
                    WxLoginEvent wxLoginEvent = new WxLoginEvent();
                    wxLoginEvent.code = resp.code;
                    EventBus.getDefault().post(wxLoginEvent);
                }
            }else if (errCode == BaseResp.ErrCode.ERR_USER_CANCEL){
                if (baseResp.transaction == "login") {
                    ToastUtils.showShort("取消登录");
                }
            }else if (errCode == BaseResp.ErrCode.ERR_AUTH_DENIED){
                ToastUtils.showShort("授权失败");
            }else {
                ToastUtils.showShort(baseResp.errStr);
            }
            finish();
        }catch (Exception e){
            finish();
        }
    }
}
